/* eslint-disable @next/next/no-img-element */
'use client'

import { useState, useEffect, useCallback } from 'react'
import { useToast } from "@/components/ui/use-toast"
import { Phone, Pencil, Trash2, UserPlus } from 'lucide-react'
import CommonSelector from '@/components/CommonSelector'
import EditorModal from '@/components/EditModal'
import { Card, CardHeader, CardContent, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Button } from "@/components/ui/button"
import AlertDestructive from '@/components/AlertDestructive'

export default function UserManagement({ getUsers, initialCampuses, updateUser, addUser, deleteUser }) {
  const [users, setUsers] = useState([])
  const [filteredUsers, setFilteredUsers] = useState([])
  const [loading, setLoading] = useState(false)
  const [branchCampusId, setBranchCampusId] = useState(null)
  const [status, setStatus] = useState(null)
  const [role, setRole] = useState(null)
  const [nameSearch, setNameSearch] = useState('')
  const [error, setError] = useState(null)
  const { toast } = useToast()

  const validatePhone = (phone) => {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
  };

  const handleSearch = () => {
    fetchUsers()
  }

  const fetchUsers = useCallback(async () => {
    setLoading(true)
    const result = await getUsers({
      branch_campus_id: branchCampusId,
      status: status,
      role: role
    })
    setUsers(result)
    setFilteredUsers(result)
    setLoading(false)
  }, [branchCampusId, status, role])

  useEffect(() => {
    fetchUsers()
  }, [fetchUsers])

  const handleNameSearch = (name) => {
    setNameSearch(name)
    if (!name.trim()) {
      setFilteredUsers(users)
      return
    }

    const filtered = users.filter(user =>
      user.name && user.name.toLowerCase().includes(name.toLowerCase())
    )
    setFilteredUsers(filtered)
  }

  const handleUpdate = async (userData) => {
    const userId = userData.id;
    try {
      const result = await updateUser(userId, userData)
      if (result.error) {
        toast({
          variant: "destructive",
          title: "更新失败",
          description: result.error,
        })
        return { success: false, message: result.error }
      } else {
        const updatedUsers = users.map(user =>
          user.id === userId ? { ...user, ...userData } : user
        )
        setUsers(updatedUsers)

        // 同时更新过滤后的用户列表
        setFilteredUsers(updatedUsers.filter(user =>
          !nameSearch.trim() || (user.name && user.name.toLowerCase().includes(nameSearch.toLowerCase()))
        ))

        return { success: true }
      }
    } catch (err) {
      toast({
        variant: "destructive",
        title: "更新失败",
        description: "更新用户失败",
      })
      return { success: false, message: '更新用户失败' }
    }
  }

  const handleDelete = async (userId, userName) => {
    try {
      const result = await deleteUser(userId)
      if (result.error) {
        toast({
          variant: "destructive",
          title: "删除失败",
          description: result.error,
        })
        return { success: false, message: result.error }
      } else {
        const updatedUsers = users.filter(user => user.id !== userId)
        setUsers(updatedUsers)

        // 同时更新过滤后的用户列表
        setFilteredUsers(updatedUsers.filter(user =>
          !nameSearch.trim() || (user.name && user.name.toLowerCase().includes(nameSearch.toLowerCase()))
        ))

        toast({
          title: "删除成功",
          description: `用户 ${userName} 已被删除`,
        })
        return { success: true }
      }
    } catch (err) {
      toast({
        variant: "destructive",
        title: "删除失败",
        description: "删除用户失败",
      })
      return { success: false, message: '删除用户失败' }
    }
  }

  const handleAdd = async (userData) => {
    try {
      const result = await addUser(userData)
      if (result.error) {
        toast({
          variant: "destructive",
          title: "添加失败",
          description: result.error,
        })
        return { success: false, message: result.error }
      } else {
        // 重新获取用户列表并清空搜索条件，确保能看到新添加的用户
        setNameSearch('')
        fetchUsers() // 刷新用户列表
        toast({
          title: "添加成功",
          description: "新用户已成功添加",
        })
        return { success: true }
      }
    } catch (err) {
      toast({
        variant: "destructive",
        title: "添加失败",
        description: "添加用户失败",
      })
      return { success: false, message: '添加用户失败' }
    }
  }

  const UserForm = ({ user }) => (
    <div className="space-y-4">
      <Input type="hidden" name="id" defaultValue={user?.id} />
      <div>
        <Label>姓名</Label>
        <Input
          name="name"
          defaultValue={user?.name}
          placeholder="请输入姓名"
        />
      </div>
      {/* gender */}
      <div>
        <Label>性别</Label>
        <CommonSelector
          name="gender"
          items={[
            { label: '男', value: 'male' },
            { label: '女', value: 'female' }
          ]}
          defaultValue={user?.gender}
        />
      </div>
      <div>
        <Label>手机号码</Label>
        <Input
          name="phone_number"
          defaultValue={user?.phone_number}
          placeholder="请输入手机号码"
        />
      </div>
      <div>
        <Label>角色</Label>
        <CommonSelector
          name="role"
          items={[
            { label: '管理员', value: 'admin' },
            { label: '学员', value: 'client' },
            { label: '教练', value: 'coach' }
          ]}
          defaultValue={user?.role}
        />
      </div>
      {/* 校区 */}
      <div>
        <Label>校区</Label>
        <CommonSelector
          name="branch_campus_id"
          items={initialCampuses.map(campus => ({ label: campus.name, value: campus.id }))}
          defaultValue={user?.branch_campus_id}
        />
      </div>
      {/* 状态 */}
      <div>
        <Label>状态</Label>
        <CommonSelector
          name="status"
          items={[
            { label: '激活', value: 'active' },
            { label: '禁用', value: 'inactive' }
          ]}
          defaultValue={user?.status}
        />
      </div>
    </div>
  );

  return (
    <div className="space-y-4 flex-1 flex flex-col p-6">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold">用户管理</h1>
        <EditorModal
          title="新增用户"
          onSubmit={handleAdd}
          trigger={
            <Button>
              <UserPlus className="h-4 w-4 mr-2" />
              新增用户
            </Button>
          }
        >
          <UserForm user={{}} />
        </EditorModal>
      </div>

      {/* 搜索 */}
      <div className="flex items-center gap-2">
        <div className="w-full grid grid-cols-1 gap-2 md:grid-cols-4">
          {/* 校区 */}
          <div className='flex items-center gap-2'>
            <Label className="w-24">校区</Label>
            <CommonSelector
              onValueChange={(value) => setBranchCampusId(value)}
              items={initialCampuses.map(campus => ({ label: campus.name, value: campus.id }))}
            />
          </div>
          {/* 角色 */}
          <div className="flex flex-row items-center gap-2">
            <Label className="w-24">角色</Label>
            <CommonSelector
              onValueChange={(value) => setRole(value)}
              items={[
                { label: '管理员', value: 'admin' },
                { label: '学员', value: 'client' },
                { label: '教练', value: 'coach' }
              ]}
            />
          </div>
          {/* 状态 */}
          <div className="flex flex-row items-center gap-2">
            <Label className="w-24">状态</Label>
            <CommonSelector
              onValueChange={(value) => setStatus(value)}
              items={[
                { label: '激活', value: 'active' },
                { label: '禁用', value: 'inactive' }
              ]}
            />
          </div>
           {/* 新增人名搜索输入框 */}
      <div className="flex items-center gap-2 mt-2">
        <Label className="w-24">姓名搜索</Label>
        <div className="relative w-full max-w-sm flex-1">
          <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-4 w-4 text-gray-400"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
              />
            </svg>
          </div>
          <Input
            placeholder="输入用户姓名进行搜索"
            value={nameSearch}
            onChange={(e) => handleNameSearch(e.target.value)}
            className="pl-10 pr-10"
          />
          {nameSearch && (
            <Button
              variant="ghost"
              size="icon"
              className="absolute right-0 top-0 h-full"
              onClick={() => handleNameSearch('')}
            >
              <span className="sr-only">清除</span>
              <svg
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
                className="h-4 w-4"
              >
                <line x1="18" y1="6" x2="6" y2="18" />
                <line x1="6" y1="6" x2="18" y2="18" />
              </svg>
            </Button>
          )}
        </div>
        {nameSearch && (
          <span className="text-sm text-gray-500 whitespace-nowrap">
            找到 {filteredUsers.length} 位用户
          </span>
        )}
      </div>
          {/* 搜索按钮 */}
          <Button onClick={handleSearch}>搜索</Button>
        </div>
      </div>



      {error && (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
          {error}
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {filteredUsers.map(user => (
          <Card key={user.id}>
            <CardHeader>
              <CardTitle className="flex justify-between items-center">
                <p className="text-lg font-bold">{user.name}</p>
                <div className="flex gap-2">
                  <EditorModal
                    title="编辑用户"
                    onSubmit={handleUpdate}
                    trigger={
                      <Button variant="ghost" size="icon">
                        <Pencil className="h-4 w-4" />
                      </Button>
                    }
                  >
                    <UserForm user={user} />
                  </EditorModal>

                  {/* <EditorModal
                    title="删除用户"
                    onSubmit={() => handleDelete(user.id, user.name)}
                    trigger={
                      <Button variant="ghost" size="icon">
                        <Trash2 className="h-4 w-4 text-red-500" />
                      </Button>
                    }
                  >
                    <AlertDestructive
                      title="删除用户"
                      message={`您确定要删除用户 ${user.name} 吗？此操作不可撤销。`}
                    />
                  </EditorModal> */}
                </div>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                {/* gender */}
                <div className='flex item-center gap-2'>
                  <Label className="w-24">性别：</Label>
                  <span>{user.gender || '未设置'}</span>
                </div>
                {/* 校区 */}
                <div className="flex items-center gap-2">
                  <Label className="w-24">校区：</Label>
                  <span>{initialCampuses.find(campus => campus.id === user.branch_campus_id)?.name || '未设置'}</span>
                </div>
                {/* 状态 */}
                <div className="flex items-center gap-2">
                  <Label className="w-24">状态：</Label>
                  <span>{user.status || '未设置'}</span>
                </div>
                {/* 手机号码 */}
                <div className="flex items-center gap-2">
                  <Label className="w-24">手机号码：</Label>
                  <span>{user.phone_number || '未设置'}</span>
                </div>
                {/* 角色 */}
                <div className="flex items-center gap-2">
                  <Label className="w-24">角色：</Label>
                  <span>{
                    {
                      'admin': '管理员',
                      'client': '学员',
                      'coach': '教练'
                    }[user.role] || user.role
                  }</span>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {loading && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
          <div className="bg-white p-4 rounded">
            处理中...
          </div>
        </div>
      )}
    </div>
  )
}